//
//  LevelScene.cpp
//  BayMaxPuzzle
//
//  Created by Jacky on 15/3/28.
//
//

#include "LevelScene.h"
#include "GameScene.h"
#include "ConfigManager.h"

USING_NS_CC;
using namespace ui;

Scene* LevelScene::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();
    
    // 'layer' is an autorelease object
    auto layer = LevelScene::create();
    
    // add layer as a child to scene
    scene->addChild(layer);
    
    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool LevelScene::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    
    initLevelDatas();
    
    initPageview();
    
    initBalls();
    
    return true;
}

void LevelScene::initLevelDatas()
{
    _leveldatas[0][0] = {3, 3};
    _leveldatas[0][1] = {3, 3};
    _leveldatas[0][2] = {3, 3};
    _leveldatas[0][3] = {3, 3};
    _leveldatas[0][4] = {3, 3};
    _leveldatas[0][5] = {3, 3};
    _leveldatas[0][6] = {3, 3};
    _leveldatas[0][7] = {3, 3};
    _leveldatas[1][0] = {4, 4};
    _leveldatas[1][1] = {4, 4};
    _leveldatas[1][2] = {4, 4};
    _leveldatas[1][3] = {4, 4};
    _leveldatas[1][4] = {4, 4};
    _leveldatas[1][5] = {4, 4};
    _leveldatas[1][6] = {4, 4};
    _leveldatas[1][7] = {4, 4};
    _leveldatas[2][0] = {5, 5};
    _leveldatas[2][1] = {5, 5};
    _leveldatas[2][2] = {5, 5};
    _leveldatas[2][3] = {5, 5};
    _leveldatas[2][4] = {5, 5};
    _leveldatas[2][5] = {5, 5};
    _leveldatas[2][6] = {5, 5};
    _leveldatas[2][7] = {5, 5};
}

void LevelScene::gotoLevel(int chapter, int section)
{
    auto leveldata = _leveldatas[chapter][section];
    Director::getInstance()->replaceScene(TransitionFade::create(0.5,GameScene::createScene(chapter, section, leveldata.rows, leveldata.cols), Color3B(255,255,255)));
}

void LevelScene::initPageview()
{
    Size visibleSize = Director::getInstance()->getVisibleSize();
    
    auto bk = Sprite::create("main.png");
    bk->setAnchorPoint(Vec2(1, 0.5));
    bk->setPosition(Vec2(visibleSize.width, visibleSize.height/2));
    bk->setScale(getRealScale(bk->getContentSize().width));
    this->addChild(bk);

    // Create the page view
    _pageView = PageView::create();
    _pageView->setContentSize(visibleSize);
    _pageView->setAnchorPoint(Vec2(0.5,0.5));
    _pageView->setPosition(visibleSize/2);
    _pageView->removeAllPages();
    
    _pageCount = CHAPTER+1;
    for (int i = 0; i < _pageCount; ++i)
    {
        auto outerBox = HBox::create();
        outerBox->setContentSize(Size(visibleSize.width, visibleSize.height/2));
        _pageView->insertPage(outerBox,i);
        
        if(i == _pageCount-1) {
            auto label = Label::createWithBMFont("konqa32.fnt", "COMMING SOON");
            label->setScale(2);
            label->setPosition(Vec2(visibleSize/2));
            outerBox->addChild(label);
            label->runAction(RepeatForever::create(Sequence::create(FadeIn::create(0.5), FadeOut::create(0.5), nullptr)));
            continue;
        }
        
        for (int k = 0; k < 2; ++k) {
            auto innerBox = VBox::create();
            
            for (int j = 0; j < 4; j++) {
                auto buttonBox = HBox::create();
                char buffer[20];
                sprintf(buffer, "%d_%d_thumbnail.png", i, j+4*k);
                auto *btn = Button::create(buffer, buffer);
                btn->setTag(j+4*k);
                btn->setPressedActionEnabled(true);
                btn->addTouchEventListener([=](Ref *pSender, Widget::TouchEventType type){
                    if (type == Widget::TouchEventType::ENDED) {
                        AUDIOENGINE_PLAY_BUTTON_FX;
                        gotoLevel(_pageView->getCurPageIndex(), static_cast<Button*>(pSender)->getTag());
                    }
                });
                buttonBox->addChild(btn);
                
                std::string text = "未通过";
                int timeCount = ConfigManager::getInstance()->getConfig(i, j+4*k);
                if(timeCount) text = convertTimeFromIntToStr(timeCount);
                auto label = Label::createWithSystemFont(text, "Arial", 20);
                label->setAnchorPoint(Vec2(0.5,0.5));
                label->setTextColor(Color4B(0,0,0,200));
                label->setPosition(Vec2(165*getHeightScale()/2,-207*getHeightScale()+20));
                buttonBox->addChild(label);
                
                innerBox->addChild(buttonBox);
                LinearLayoutParameter *parameter = LinearLayoutParameter::create();
                int MARGIN = 200;
                parameter->setMargin(Margin(visibleSize.width/2-1.5*MARGIN-165/2*getHeightScale()+MARGIN*j,0,0,0));
                buttonBox->setLayoutParameter(parameter);
            }
            
            LinearLayoutParameter *parameter = LinearLayoutParameter::create();
            parameter->setMargin(Margin(0,50+250*k,0,0));
            innerBox->setLayoutParameter(parameter);
            
            outerBox->addChild(innerBox);
            
        }
        
    }
    
    _pageView->setCustomScrollThreshold(150);
    _pageView->addEventListener(CC_CALLBACK_2(LevelScene::pageViewEvent, this));
    
    this->addChild(_pageView);
}

void LevelScene::initBalls()
{
    Size visibleSize = Director::getInstance()->getVisibleSize();
    int MARGIN = 50;
    for (int i=0; i<CHAPTER+1; i++) {
        _indexBall[i] = Sprite::create("ball.png");
        _indexBall[i]->setScale(0.9);
        _indexBall[i]->setColor(Color3B(100,100,100));
        _indexBall[i]->setOpacity(100);
        _indexBall[i]->setPosition(Vec2(visibleSize.width/2-1.5*MARGIN+MARGIN*i, 80));
        _indexBall[i]->setTag(i);
        this->addChild(_indexBall[i]);
    }
    _curIndexBall = Sprite::create("ball.png");
    _curIndexBall->setPosition(_indexBall[0]->getPosition());
    this->addChild(_curIndexBall);
}

void LevelScene::pageViewEvent(Ref *pSender, PageView::EventType type)
{
    switch (type)
    {
        case PageView::EventType::TURNING:
        {
            PageView* pageView = dynamic_cast<PageView*>(pSender);
            _curIndexBall->runAction(MoveTo::create(0.1, _indexBall[pageView->getCurPageIndex()]->getPosition()));
        }
            break;
            
        default:
            break;
    }
}

std::string LevelScene::convertTimeFromIntToStr(int time){
    int hour = time/3600;
    int last = time%3600;
    int min = last/60;
    int sec = last%60;
    char buffer[20];
    sprintf(buffer, "%02d:%02d:%02d",hour,min,sec);
    std::string str(buffer);
    return str;
}

float LevelScene::getHeightScale()
{
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Size designSize = Director::getInstance()->getOpenGLView()->getDesignResolutionSize();
    float originScale = visibleSize.height/designSize.height;
    return originScale;
}

float LevelScene::getRealScale(int picWidth)
{
    float scale = 0;
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Size designSize = Director::getInstance()->getOpenGLView()->getDesignResolutionSize();
    float originScale = visibleSize.height/designSize.height;
    picWidth *= originScale;
    if(picWidth>visibleSize.width)
    {
        scale = 1;
    }
    else{
        scale = visibleSize.width/picWidth;
    }
    return scale;
}
